<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Leiniao extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        ksort($array);
        $sign_str = urldecode(http_build_query($array));
        $sign_str .= '@' . $secret_key;
        return md5($sign_str);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $type = match (true) {
            preg_match("/^1[34578]\d{9}$/", $bean->getAccount()) => 6,
            preg_match("/^[1-9]\d{4,10}$/", $bean->getAccount()) => 1,
            preg_match("/^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/", $bean->getAccount()) => 5,
            default => 0,
        };
        $array = [
            'merchantNo'            => $bean->getSupplierNum(), //商户密钥
            'merchantOrderNo'       => $bean->getOrderNo(), //订单号
            'merchantOrderPrice'    => $bean->getRechargeNum() * $bean->getStartCharging() * $bean->getUnitPrice(),
            'merchantPayTime'       => millisecondTimestamp(),
            'userType'              => $type,
            'userId'                => $bean->getAccount(),
            'operType'              => 1,
            'serviceProviderType'   => $bean->getGoodsId(), //商品编码
            'days'                  => $bean->getDashangAccountType(),
            'times'                 => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量,
            'appId'                 => '',
            'callbackUrl'           => $bean->getNotifyUrl(), //异步回调地址
        ];
        $array['signature'] = $this->sign($array, $bean->getSecretKey());
        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('orderStatus', '');
        $order_sn = $request->input('merchantOrderNo', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, [1, -1]))->setRechargeSuccess($status == 1);
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('success');
    }
}
